package com.example.club_mvvm.base

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.club_mvvm.http.BaseResponse
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.onStart
import kotlinx.coroutines.launch


/**
 * @author yaotianxue
 * @description
 * @date 2025/1/11
 */
open class BaseViewModel:ViewModel() {//类默认不能被继承，open才可以
    //<M:BaseResponse<T>,T> 泛型约束
    //execute 高阶函数：参数或者返回值是函数类型的函数
    fun <M:BaseResponse<T>,T> execute(
        action: Flow<M>,
        onStart:(suspend ()->Unit)? = null,
        onError:(suspend (String)->Unit)? = null,
        onFinished:(suspend (M)->Unit)? = null
    ) = viewModelScope.launch {
        action.onStart { //开始
            onStart?.invoke()
        }.catch { err->
            onError?.invoke(err.message.toString())
        }.collectLatest { it->
            if(it.code == 200){
                onFinished?.invoke(it)
            }else{
                onError?.invoke(it.message)
            }
        }
    }
}